#include "usart.h"
#include "store.h"
#include "norflash.h"
#include "printf.h"
#include <stdlib.h>
#include <string.h>
extern char sprintf_buffer[100];
void output_str(const char* str,uint16_t len);
void cmd_baudRate(int argc, char** argv){
    int len;
    if(argc == 1){
        const char put[] = "当前波特率:\r\n";
        output_str(put, sizeof(put));
        len = sprintf(sprintf_buffer, "UART1: %d\r\n", (int)huart1.Init.BaudRate);
        output_str(sprintf_buffer, len);
        len = sprintf(sprintf_buffer, "UART2: %d\r\n", (int)huart2.Init.BaudRate);
        output_str(sprintf_buffer, len);
    }
    else if(argc == 2){
        if(strcmp(argv[1], "1") == 0){
            len = sprintf(sprintf_buffer, "UART1: %d\r\n", (int)huart1.Init.BaudRate);
            output_str(sprintf_buffer, len);
        }
        else if(strcmp(argv[1], "2") == 0){
            len = sprintf(sprintf_buffer, "UART2: %d\r\n", (int)huart2.Init.BaudRate);
            output_str(sprintf_buffer, len);
        }
        else{
            const char put[] = "参数错误\r\n";
            output_str(put, sizeof(put));
        }
    }
    else if(argc == 3){
        int baudRate = atoi(argv[2]);
        if(baudRate < 1200 || baudRate > 961200){
            const char put[] = "波特率范围需要为1200~961200\r\n";
            output_str(put, sizeof(put));
            return;
        }
        if(strcmp(argv[1], "1") == 0){
            huart1.Init.BaudRate = baudRate;
            if(HAL_UART_Init(&huart1) != HAL_OK){
                const char put[] = "设置失败\r\n";
                output_str(put, sizeof(put));
                return;
            }
            uint32_t baudrate = huart1.Init.BaudRate;
            norflash_write((uint8_t*)&baudrate,BAUDRATE_ADDR,4);
            len = sprintf(sprintf_buffer, "串口1波特率设置为: %d\r\n",(int)huart1.Init.BaudRate);
            output_str(sprintf_buffer, len);
        }
        else if(strcmp(argv[1], "2") == 0){
            huart2.Init.BaudRate = baudRate;
            if(HAL_UART_Init(&huart2) != HAL_OK){
                const char put[] = "设置失败\r\n";
                output_str(put, sizeof(put));
                return;
            }
            uint32_t baudrate = huart2.Init.BaudRate;
            norflash_write((uint8_t*)&baudrate,BAUDRATE_ADDR+4,4);
            len = sprintf(sprintf_buffer, "串口2波特率设置为: %d\r\n",(int)huart2.Init.BaudRate);
            output_str(sprintf_buffer, len);
        }
        else{
            const char put[] = "参数错误\r\n";
            output_str(put, sizeof(put));
        }
    }
    else{
        const char put[] = "参数错误\r\n";
        output_str(put, sizeof(put));
    }
}